package main

import (
    "io"
    "log"
    "flag"
    "encoding/json"
    "net/http"
    "net/url"
)

const gaeproxy = "http://xlionoil.appspot.com"
const localproxy = "http://localhost:8080"
var proxy string

func main() {
    b := flag.Bool("l", false, "turn to local proxy")
    flag.Parse()

    http.HandleFunc("/", proxyHandler)
    if *b {
        log.Println("> lacal proxy starts")
        proxy = localproxy
    } else {
        log.Println("> gae proxy starts")
        proxy = gaeproxy
    }

    log.Fatal("> ", http.ListenAndServe(":8000", nil))
}

func proxyHandler(w http.ResponseWriter, r *http.Request) {
    logURL := r.URL.String()
    if len(logURL) > 50 {
        logURL = logURL[:50]
    }
    log.Println(">", r.Method, logURL, "...")
    client := &http.Client{}
    r.RequestURI = ""
    uJson, _ := json.Marshal(r.URL)
    r.Header.Add("xlionoil", string(uJson))
    r.URL, _ = url.Parse(proxy)
    r.Host = r.URL.Host

    resp, err := client.Do(r)
    if err != nil {
        log.Printf("> error: %s", err)
        w.WriteHeader(http.StatusNotFound)
        w.Write([]byte("Page not found"))
        return
    }
    for key, value := range(resp.Header) {
        for _, vv := range(value) {
            w.Header().Add(key, vv)
        }
    }
    w.WriteHeader(resp.StatusCode)
    io.Copy(w, resp.Body)
    resp.Body.Close()
}
